﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Media;
using FirstFloor.Documents.Fonts;
using SampleBrowser.Util;

namespace SampleBrowser.Views
{
    public partial class SampleFontDetails : Page
    {
        private FontFamily currentFontFamily;
        private FontSource currentFontSource;

        public SampleFontDetails()
        {
            InitializeComponent();

            var fonts = FontResourceInfo.AllFonts(GetType().Assembly).ToArray();
            this.cmbFont.ItemsSource = fonts;
            this.cmbFont.SelectedItem = fonts.First();
        }

        private void cmbFont_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var font = (FontResourceInfo)this.cmbFont.SelectedItem;
            if (font != null) {
                ShowFontDetails(font.FontStream);
            }
        }

        private void ShowFontDetails(Stream fontStream)
        {
            // use font parser to create a typeface
            var fontInfo = FontParser.ParseFontInfo(fontStream);
            var typeface = FontParser.ParseFontFace(fontInfo, 0);

            // databind to UI
            var localizedTypeface = typeface.GetDefaultLocalizedTypeface();
            this.FontType.DataContext = fontInfo;
            this.DataContext = localizedTypeface;
            this.currentFontFamily = new FontFamily(localizedTypeface.FamilyName);
            this.currentFontSource = new FontSource(fontStream);

            UpdateSampleTexts();
        }

        private void UpdateSampleTexts()
        {
            foreach (var text in GetSampleTexts()) {
                if (text != null) {
                    text.FontFamily = this.currentFontFamily;
                    text.FontSource = this.currentFontSource;
                }
            }
        }

        private IEnumerable<TextBlock> GetSampleTexts()
        {
            for (int i = 1; i <= 9; i++) {
                yield return (TextBlock)this.FindName(string.Format("sample{0}", i));
            }
        }

        private void sampleTexts_Loaded(object sender, System.Windows.RoutedEventArgs e)
        {
            UpdateSampleTexts();
        }

        private void FromDisk_Click(object sender, RoutedEventArgs e)
        {
            try {
                var stream = FontHelper.OpenFontFromDisk();
                if (stream != null) {
                    ShowFontDetails(stream);

                    this.cmbFont.SelectedValue = null;
                }
            }
            catch (Exception error) {
                new ErrorWindow(error).Show();
            }
        }
    }
}
